//
//  NDAddressPickerView.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/13.
//

import SwiftUI

// MARK: - 配置
struct NDAddressPickerConfig {
    var title: String = localizedString("Select the address")
    var provincePlaceholder = localizedString("Choose")
    var cityPlaceholder = localizedString("Choose")
    var districtPlaceholder = localizedString("Choose")
    var separatorText: String = ""
    var placeholderColor: Color = Color(hex: "#FD632B")
    var selectedColor: Color = Color(hex: "#271F24")
    var selectedBackgroundColor: Color = Color.clear
    var placeholderBackgroundColor: Color = Color.clear
    var confirmButtonColor: Color = Color(hex: "#1E4FF3")
    var confirmButtonText: String = localizedString("Confirm")
    // 选择限制配置
    var requireFullSelection: Bool = true
    var minSelectionLevel: Int = 1
}

// MARK: - 回调处理器
struct NDAddressPickerActions {
    var onSelectItem: ((NDAddressItem, Int) -> Void)? = nil
    var onCompleteSelection: (([NDAddressItem]) -> Void)? = nil
    var onClickConfirmButton: (([NDAddressItem]) -> Void)? = nil
    var onSelectionError: ((String) -> Void)? = nil
    var onCloseAction: (() -> Void)?
    
    static let empty = NDAddressPickerActions()
}

// MARK: - 主选择器视图
struct NDAddressPickerView: View {
    // MARK: 配置和回调
    let config: NDAddressPickerConfig
    let actions: NDAddressPickerActions
    
    // MARK: 状态管理
    @State private var dataSource: [NDAddressItem] = []
    @State private var selectedPath: [NDAddressItem] = []
    @State private var currentLevelData: [NDAddressItem] = []
    @State private var maxLevel: Int = 3
    @State private var isConfirmEnabled: Bool = false
    
    // MARK: 初始化
    init(
        data: [NDAddressItem] = [],
        maxLevel: Int = 3,
        config: NDAddressPickerConfig = NDAddressPickerConfig(),
        actions: NDAddressPickerActions = NDAddressPickerActions()
    ) {
        self._dataSource = State(initialValue: data)
        self._maxLevel = State(initialValue: maxLevel)
        self.config = config
        self.actions = actions
    }
    
    var body: some View {
        VStack(spacing: 0) {
            // 自定义标题
            Spacer()
                .frame(height: 5)
            ZStack(alignment: .trailing) {
                customTitleLabel
                closeButton
            }
            // 路径显示
            pathDisplayView
            // 列表内容
            listContentView
            Spacer()
            // 确认按钮
            confirmButton
        }
        .background(Color.clear)
        .onAppear {
            setupInitialData()
            updateConfirmButtonState()
        }
        .onChange(of: selectedPath) { _ in
            updateConfirmButtonState()
        }
    }
}

// MARK: - UI 组件
private extension NDAddressPickerView {
    var customTitleLabel: some View {
        Text(config.title)
            .font(.system(size: 18, weight: .medium))
            .foregroundColor(.black)
            .frame(maxWidth: .infinity)
            .frame(height: 24)
            .padding(.top, 20)
            .padding(.horizontal, 16)
    }
    
    var pathDisplayView: some View {
        ScrollViewReader { proxy in
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 8) {
                    // 已选择的路径项
                    ForEach(Array(selectedPath.enumerated()), id: \.offset) { index, item in
                        HStack(spacing: 8) {
                            if index > 0 {
                                separatorView
                            }
                            selectedPathButton(item: item, level: index)
                        }
                    }
                    
                    // 当前级别的占位符 - 只在未达到最大层级时显示
                    ForEach(selectedPath.count..<maxLevel, id: \.self) { index in
                        HStack(spacing: 8) {
                            if !selectedPath.isEmpty || index > 0 {
                                separatorView
                            }
                            placeholderView
                        }
                    }
                    
                    Spacer(minLength: 0)
                }
                .padding(.horizontal, 16)
                .id("pathContainer")
            }
            .frame(height: 30)
            .onChange(of: selectedPath) { _ in
                scrollToEnd(using: proxy)
            }
        }
        .padding(.top, 20)
    }
    
    var listContentView: some View {
        ScrollView {
            LazyVStack(spacing: 0) {
                ForEach(currentLevelData) { item in
                    addressRow(for: item)
                        .padding(.horizontal, 16)
                }
            }
            .padding(.top, 2)
        }
        .background(Color.clear)
    }
    
    var confirmButton: some View {
        Button(action: handleConfirm) {
            Text(config.confirmButtonText)
                .frame(maxWidth: .infinity)
                .font(.system(size: 18, weight: .bold))
                .foregroundColor(Color(hex: "#FFFFFF"))
                .padding(.horizontal, 15)
                .padding(.vertical, 10)
                .frame(height: 48)
                .background(Color(hex: "#271F24"))
                .clipShape(Capsule())
                .contentShape(Rectangle())
        }
        .padding(.horizontal, 16)
        .padding(.bottom, 16)
    }

    var separatorView: some View {
        Text(config.separatorText)
            .font(.system(size: 14))
            .foregroundColor(.gray)
    }
    
    func selectedPathButton(item: NDAddressItem, level: Int) -> some View {
        Button(action: {
            // 点击路径项时，重置该级及之后的所有选择
            resetFromLevel(level)
        }) {
            Text(item.name)
                .font(.system(size: 16, weight: .semibold))
                .foregroundColor(config.selectedColor)
                .padding(.horizontal, 5)
                .padding(.vertical, 6)
                .background(config.selectedBackgroundColor)
                .cornerRadius(15.5)
        }
    }
    
    var placeholderView: some View {
        let placeholderText = getPlaceholderText()
        return Text(placeholderText)
            .font(.system(size: 16, weight: .semibold))
            .foregroundColor(config.placeholderColor)
            .padding(.horizontal, 5)
            .padding(.vertical, 6)
            .background(config.placeholderBackgroundColor)
            .cornerRadius(15.5)
    }
    
    func addressRow(for item: NDAddressItem) -> some View {
        HStack {
            Text(item.name)
                .font(.system(size: 16, weight: .medium))
                .foregroundColor(Color(hex: "#666666"))
            
            Spacer()
            
            if shouldShowDisclosure(for: item) {
                Image(systemName: "chevron.right")
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(.gray)
            }
        }
        .contentShape(Rectangle())
        .onTapGesture {
            selectItem(item)
        }
        .frame(height: 48)
    }
}

// MARK: - 业务逻辑
private extension NDAddressPickerView {
    func setupInitialData() {
        guard maxLevel >= 2 && maxLevel <= 3 else {
            fatalError("maxLevel must be 2 or 3")
        }
        currentLevelData = dataSource
    }
    
    func getPlaceholderText() -> String {
        switch selectedPath.count {
        case 0: return config.provincePlaceholder
        case 1: return config.cityPlaceholder
        case 2: return config.districtPlaceholder
        default: return ""
        }
    }
    
    func shouldShowDisclosure(for item: NDAddressItem) -> Bool {
        // 如果是叶子节点，不显示箭头
        if item.isLeaf { return false }
        // 如果已经达到最大层级-1，不显示箭头（因为下一级就是最后一级）
        if selectedPath.count >= maxLevel - 1 { return false }
        // 其他情况显示箭头
        return true
    }
    
    func selectItem(_ item: NDAddressItem) {
        let currentLevel = selectedPath.count
        
        // 关键修复：如果已经达到最大层级，不允许再添加新的层级
        guard currentLevel < maxLevel else {
            // 如果已经是最后一级，允许在同一级内切换选择
            if currentLevel == maxLevel {
                // 替换当前级别的选择
                selectedPath[currentLevel - 1] = item
                actions.onSelectItem?(item, currentLevel - 1)
                actions.onCompleteSelection?(selectedPath)
            }
            return
        }
        
        // 如果已经选择了当前级别的项目，先移除后续级别
        if selectedPath.count > currentLevel {
            selectedPath.removeSubrange(currentLevel...)
        }
        
        // 添加新选择的项目
        selectedPath.append(item)
        actions.onSelectItem?(item, selectedPath.count - 1)
        
        // 检查是否是最后一级选择
        if isSelectionComplete(for: item) {
            actions.onCompleteSelection?(selectedPath)
            // 选择完成后保持当前列表数据不变，允许用户重新选择当前级别
        } else {
            // 加载下一级数据
            loadNextLevelData(for: item)
        }
    }
    
    func isSelectionComplete(for item: NDAddressItem) -> Bool {
        // 如果达到最大层级，或者项目是叶子节点，则选择完成
        return selectedPath.count == maxLevel || item.isLeaf
    }
    
    func loadNextLevelData(for item: NDAddressItem) {
        // 关键修复：确保不会超过最大层级
        guard selectedPath.count < maxLevel else { return }
        
        if let children = item.children, !children.isEmpty {
            currentLevelData = children
        } else {
            // 如果没有子数据，认为选择完成
            actions.onCompleteSelection?(selectedPath)
        }
    }
    
    // 重置从指定层级开始的所有选择
    func resetFromLevel(_ level: Int) {
        guard level < selectedPath.count else { return }
        
        // 移除从指定层级开始的所有后续选择
        selectedPath.removeSubrange(level...)
        
        // 重置到对应层级的数据
        resetToLevel(level)
        
        // 通知回调
        if level < selectedPath.count {
            actions.onSelectItem?(selectedPath[level], level)
        }
    }
    
    func resetToLevel(_ level: Int) {
        switch level {
        case 0:
            // 重置到第一层：显示所有省份数据
            currentLevelData = dataSource
        case 1:
            // 重置到第二层：显示选中省份的城市数据
            if let province = selectedPath.first, let cities = province.children {
                currentLevelData = cities
            } else {
                currentLevelData = []
            }
        case 2:
            // 重置到第三层：显示选中城市的区县数据
            if selectedPath.count > 1, let districts = selectedPath[1].children {
                currentLevelData = districts
            } else {
                currentLevelData = []
            }
        default:
            break
        }
    }
    
    func handleConfirm() {
        // 验证选择是否符合要求
        if validateSelection() {
            actions.onClickConfirmButton?(selectedPath)
        } else {
            let errorMessage = getValidationErrorMessage()
            actions.onSelectionError?(errorMessage)
        }
    }
    
    func validateSelection() -> Bool {
        if config.requireFullSelection {
            // 要求完整选择
            return selectedPath.count == maxLevel
        } else {
            // 不要求完整选择，但至少要达到最小选择层级
            return selectedPath.count >= config.minSelectionLevel
        }
    }
    
    func getValidationErrorMessage() -> String {
        if config.requireFullSelection {
            return localizedString("Please select the complete address")
        } else {
            return "select error"
        }
    }
    
    func updateConfirmButtonState() {
        isConfirmEnabled = validateSelection()
    }
    
    func scrollToEnd(using proxy: ScrollViewProxy) {
        DispatchQueue.main.async {
            withAnimation(.easeInOut(duration: 0.3)) {
                proxy.scrollTo("pathContainer", anchor: .trailing)
            }
        }
    }
    
    private var closeButton: some View {
        Button(action: {
            actions.onCloseAction?()
        }) {
            Image(systemName: "xmark")
                .font(.system(size: 16))
                .frame(width: 20, height: 20)
                .foregroundColor(Color(hex: "#271F24"))
        }
        .padding(.top, 20)
        .padding(.trailing, 20)
    }
}

// MARK: - 示例数据扩展
extension NDAddressItem {
    static var mockProvinces: [NDAddressItem] {
        [
            NDAddressItem(
                id: "1",
                name: "北京市",
                children: [
                    NDAddressItem(id: "11", name: "北京市", children: [
                        NDAddressItem(id: "111", name: "东城区"),
                        NDAddressItem(id: "112", name: "西城区"),
                        NDAddressItem(id: "113", name: "朝阳区")
                    ])
                ]
            ),
            NDAddressItem(
                id: "2",
                name: "上海市",
                children: [
                    NDAddressItem(id: "21", name: "上海市", children: [
                        NDAddressItem(id: "211", name: "黄浦区"),
                        NDAddressItem(id: "212", name: "徐汇区")
                    ])
                ]
            ),
            NDAddressItem(
                id: "3",
                name: "广东省",
                children: [
                    NDAddressItem(id: "31", name: "广州市", children: [
                        NDAddressItem(id: "311", name: "天河区"),
                        NDAddressItem(id: "312", name: "越秀区")
                    ]),
                    NDAddressItem(id: "32", name: "深圳市", children: [
                        NDAddressItem(id: "321", name: "福田区"),
                        NDAddressItem(id: "322", name: "南山区")
                    ])
                ]
            )
        ]
    }
}

